/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name one by one, they are:
 *  dyeOrder
 *  DyeOrder
 *  dye_order
 */



/***** variables declartion section, begin *****/
var dyeOrderItemInputMode = wacFormInputMode.add;
var dyeOrderItemObj = {};
var dyeOrderObj = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        initDyeOrderItemFormDialog();

        initDyeOrderItemForm();

        bindDyeOrderItemEvents();
    }
);

function bindDyeOrderItemEvents()
{
    $("#dyeOrderItemFormDialog").bind('dialogopen', function(event, ui)
    {
        initDyeOrderItemFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.dyeOrderItem.name);//
    });

    $("#dyeOrderItemFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#dyeOrderItem_btnSubmit").bind('click', function (e)
    {
        submitDyeOrderItemForm();
    });

    $("#dyeOrderItem_btnClose").bind('click', function (e)
    {
        $("#dyeOrderItemFormDialog").dialog('close');
    });

    $("#dyeOrderItem_goods_number, #dyeOrderItem_goods_number_unit_price").bind('change', function (e)
    {
        $("#dyeOrderItem_processing_fee").attr("value", Number($("#dyeOrderItem_goods_number").val()) * Number($("#dyeOrderItem_goods_number_unit_price").val()));
        $("#dyeOrderItem_processing_fee").formatCurrency({symbol:"",digitGroupSymbol:"", roundToDecimalPlace:-1});
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t12003")
        {
            $("div[aria-labelledby='ui-dialog-title-dyeOrderItemFormDialog']").remove();
            $("#dyeOrderItemFormDialog").remove();
        }
    });
}


function initDyeOrderItemFormDialog()
{
//    wacDebugLog("initDyeOrderItemFormDialog.");
    $("#dyeOrderItemFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 1060,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initDyeOrderItemForm()
{
    $("#dyeOrderItemForm").validationEngine();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initDyeOrderItemFormData()
{
    wacShowBlockUILoading("#dyeOrderItemFormDialog");
    $('#dyeOrderItem_axis_id, #dyeOrderItem_cotton_goods_id, #dyeOrderItem_color_id, #dyeOrderItem_jar_id, #dyeOrderItem_goods_id, #dyeOrderItem_goods_number_unit_code').empty();

    var params = {
        "data_format" : 'json',
        "dye_order_id": dyeOrderObj.id
    };

    $.ajax({
        url: BASE_URL + "dyeOrderItem/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initDyeOrderItemFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initDyeOrderItemFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['axis'].length;i++)
        {
            $('<option value="' + jsonData['items']['axis'][i].key +'">' + jsonData['items']['axis'][i].value +'</option>').appendTo("#dyeOrderItem_axis_id");
        }

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#dyeOrderItem_goods_number_unit_code");
        }

        for(i=0;i<jsonData['items']['cotton_stock_goods'].length;i++)
        {
            $('<option value="' + jsonData['items']['cotton_stock_goods'][i].key +'">' + jsonData['items']['cotton_stock_goods'][i].value +'</option>').appendTo("#dyeOrderItem_cotton_goods_id");
        }
   }

   setupDyeOrderItemFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#dyeOrderItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupDyeOrderItemFormDefaultValues(defaultValueObj)
{
    $("#dyeOrderItem_dye_order_id").attr("value", dyeOrderObj.id);
    $("#dyeOrderItem_dye_order_code").attr("innerHTML", dyeOrderObj.code);
    $("#dyeOrderItem_production_order_code").attr("innerHTML", dyeOrderObj.production_order_code);
    $("#dyeOrderItem_supplier_name").attr("innerHTML", dyeOrderObj.supplier_name);

    if(dyeOrderItemInputMode == wacFormInputMode.add)   // use default values
    {
        $("#dyeOrderItem_id").attr("value", 0);
        $('#dyeOrderItem_goods_id').flexbox(BASE_URL + 'goods/GetDyeHashInFormat?data_format=jsonFlexbox&parent=class_dye', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#dyeOrderItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            inputName: "jar_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#dyeOrderItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            inputName: "color_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#dyeOrderItem_goods_number_unit_code option:[value='"+ dyeOrderObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#dyeOrderItem_axis_id option:[value='"+ defaultValueObj.axis_id +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#dyeOrderItem_goods_id').flexbox(BASE_URL + 'goods/GetDyeHashInFormat?data_format=jsonFlexbox&parent=class_dye', {
            initialValue: dyeOrderItemObj.goods_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dyeOrderItem_goods_id_input').val(dyeOrderItemObj.goods_name);

        $('#dyeOrderItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: dyeOrderItemObj.jar_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            inputName: "jar_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dyeOrderItem_jar_id_input').val(dyeOrderItemObj.jar_name);

        $('#dyeOrderItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: dyeOrderItemObj.color_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            inputName: "color_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dyeOrderItem_color_id_input').val(dyeOrderItemObj.color_name);

//        $("#dyeOrderItem_batch").attr("value", dyeOrderItemObj.batch);
        $("#dyeOrderItem_goods_number_unit_price").attr("value", dyeOrderItemObj.goods_number_unit_price);
        $("#dyeOrderItem_goods_number").attr("value", dyeOrderItemObj.goods_number);
        $("#dyeOrderItem_id").attr("value", dyeOrderItemObj.id);

        $("#dyeOrderItem_quota_amount").attr("value", dyeOrderItemObj.quota_amount);
        $("#dyeOrderItem_processing_fee").attr("value", dyeOrderItemObj.processing_fee);
        $("#dyeOrderItem_wheelbase").attr("value", dyeOrderItemObj.wheelbase);
        $("#dyeOrderItem_axis_time").attr("value", dyeOrderItemObj.axis_time);
        $("#dyeOrderItem_cotton_yarn_consume_amount").attr("value", dyeOrderItemObj.cotton_yarn_consume_amount);
        $("#dyeOrderItem_cotton_yarn_unit_consume").attr("value", dyeOrderItemObj.cotton_yarn_unit_consume);
        $("#dyeOrderItem_cotton_yarn_expect_consume").attr("value", dyeOrderItemObj.cotton_yarn_expect_consume);
        $("#dyeOrderItem_attrition_rate").attr("value", dyeOrderItemObj.attrition_rate);
        $("#dyeOrderItem_memo").attr("value", dyeOrderItemObj.memo);

        $("#dyeOrderItem_cotton_goods_id option:[value='"+ dyeOrderItemObj.cotton_goods_id +"']").attr('selected', 'selected');
        $("#dyeOrderItem_goods_number_unit_code option:[value='"+ dyeOrderItemObj.goods_number_unit_code +"']").attr('selected', 'selected');
        $("#dyeOrderItem_axis_id option:[value='"+ dyeOrderItemObj.axis_id +"']").attr('selected', 'selected');
    }

//wacDebugLog($.dump(dyeOrderItemObj));
//    wacDebugLog($.dump(dyeOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("dyeOrderItemInputMode: " + dyeOrderItemInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

function dyeOrderItemOpenModuleForm(moduleFormName, moduleName, inputMode, rowid, parentId)
{
    dyeOrderItemInputMode = inputMode;

    if(parentId === undefined || parentId==0){
        dyeOrderObj = {};
    }
    else
    {
        dyeOrderObj = $("#dyeOrderList").getRowData(parentId);
    }

    if(rowid === undefined || rowid==0){
        dyeOrderItemObj = {};
    }
    else
    {
        dyeOrderItemObj = $("#dyeOrderList_" + dyeOrderObj.id + "_t").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateDyeOrderItemForm()
{
    var validateFlag = true;

    if (!$("#dyeOrderItemForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    return validateFlag;
}

function submitDyeOrderItemForm()
{
    if(!validateDyeOrderItemForm()){
        return;
    }

    wacShowBlockUILoading("#dyeOrderItemFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(dyeOrderItemInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "dyeOrderItem/add";
    }
    else{
        submitUrl = BASE_URL + "dyeOrderItem/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#dyeOrderItemForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitDyeOrderItemFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitDyeOrderItemFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#dyeOrderList_" + dyeOrderObj.id + "_t").trigger("reloadGrid");
   }

   wacHideBlockUI("#dyeOrderItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/